<?php
class Admini_ManagetaobaoController extends Uuch_BaseController{    
    
    public function init() {
        echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
    }
    

    public function  indexAction()
    {
        Application_Model_Operate::addOperate(0, null, null, "更新淘宝订单的物流信息", null);
        echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
        $orderItem = Application_Model_Order::getAllOrder();
        $taobao = new Uuch_Reader_TaobaoReader();
        $arrSign = Application_Model_Taobaoapi::getSignAll();
        foreach ($orderItem as  $orderval) {
            $taobaoid = substr($orderval->procureNo, -4);
            if(!in_array($taobaoid, $arrSign)){
                echo $orderval->procureNo."不是淘宝订单<br>";
                continue;
            }
            $result = $taobao->taobaowlxx($orderval->procureNo,'managetaobao/index');
            if($result && $result->code){
                echo $orderval->procureNo." sessionkey已过期<br>";
                continue;
            }
            if(!$result->trade->orders){
                continue;
            }
            $logistics_company = $result->trade->orders->order;
            if (!$logistics_company) {
                $logistics_company = $result->trade->orders->order[1];
            }
            if(!$logistics_company) {
                echo "代购中淘宝订单为" . $orderval->procureNo . "的卖家未发货<br>";
                continue;
            }
            foreach ($logistics_company->logistics_company as $key => $nameval) {
                $shipresult = Application_Model_shipType::getByName($nameval);
                $orderval->logistics = 181; 
                if ($shipresult) {
                    $orderval->logistics = $shipresult->id;
                    continue;
                }
            }
            $invoice_no = $logistics_company->invoice_no;
            if (!$invoice_no) {
                $invoice_no = $logistics_company->invoice_no;
            }
            if (!$invoice_no) {
                echo "代购中淘宝订单为" . $orderval->procureNo . "的卖家未发货<br>";
                continue;
            }
            foreach ($invoice_no as $key => $noval) {
                $orderval->logisticsNo = $noval;
            }
            $orderval->consignTime = (string)$result->trade->consign_time;
            $orderval->status = Application_Model_Order::STATUS_SELLER_SENDED;
            $orderval->save();
            echo "代购中淘宝订单为" . $orderval->procureNo . "的卖家发货的物流已更新(物流公司：$nameval 物流单号：$orderval->logisticsNo )<br>";            
        }
        exit;
    }
    
    public function  indexoneAction()
    {
        $id = $this->getSafeParam("id");
        echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
        $orderItem = Application_Model_Order::load($id);
        $taobao = new Uuch_Reader_TaobaoReader();
        $arrSign = Application_Model_Taobaoapi::getSignAll();
        $taobaoid = substr($orderItem->procureNo, -4);
        if(in_array($taobaoid, $arrSign)){
             $result = $taobao->taobaowlxx($orderItem->procureNo,'managetaobao/indexindexone');
            var_dump($result);
            echo "<br>";
             $logistics_company = $result->trade->orders->order;
            if (!$logistics_company) {
                $logistics_company = $result->trade->orders->order[1];
            }
            foreach ($logistics_company->logistics_company as $key => $nameval) {
                $shipresult = Application_Model_shipType::getByName($nameval);
                $logistics = 181; 
                if ($shipresult) {
                    $logistics = $shipresult->id;
                    continue;
                }
            }
            echo $logistics."<br>";
            var_dump($logistics_company);exit;
            
        }else{
            echo $orderval->procureNo."不是淘宝订单<br>";
        }
        
        exit;
    }
    
    public function extendtaobaoAction()
    {
        Application_Model_Operate::addOperate(0, null, null, "延长淘宝SessionKet的有效期", null);
        $taobao = new Uuch_Reader_TaobaoReader();
        $result = $taobao->getTaobaoToken();
        exit;
    }
    
    public function costpriceAction() 
    {
        Application_Model_Operate::addOperate(0, null, null, "获取渠道商的成本价", null);
        $agentcompany = Application_Model_AgentCompany::getAgentAll();
        foreach ($agentcompany as $agentval) {
            if($agentval->host != null){
                $costpriceMt = Application_Model_CostPrice::byMaxTime($agentval->id); 
                $singleMt = Application_Model_Single::byMaxTime($agentval->id);
                $obj = new Uuch_KingTransAPI($agentval->host,$agentval->username, $agentval->password);
                $maxdate = date('Y-m-d');
                if ($singleMt < $maxdate) {
                    $stime = strtotime($singleMt);
                    $etime = strtotime($maxdate);
                    for ($i = $stime; $i < $etime; $i++) {
                        $single = new singleFilter();
                        $single->datetime = date("Y-m-d", $i);
                        $result = false;
                        if($agentval->name == "互联易"){
                            $result = $obj->getSingleHly($single);
                        }else if($agentval->name == "圣达"){
                            $result = $obj->getSingleSd($single);
                        }else if($agentval->name == "易邮"){
                            $result = $obj->getSingleSd($single);
                        }
                        if ($result) {
                            foreach ($result as $singvalue) {
//                                var_dump($singvalue);exit;
                                $outstoreno = iconv("GB2312//IGNORE", "UTF-8", $singvalue->outstoreno);
                                $singleItem = Application_Model_Single::bySingle($outstoreno);
                                if($singleItem == ""){
                                    $singleItem = new Application_Model_Single();
                                }
                                $singleItem->agentid = $agentval->id;
                                foreach ($singvalue as $key => $value) {
                                    $singleItem->$key = iconv("GB2312//IGNORE", "UTF-8", $value);
                                }
                                if (strpos($singleItem->channel, "联邦") > 0 || strpos($singleItem->channel, "联邦") === 0) {
                                    if ($singleItem->turnno != "" && strlen($singleItem->turnno) == 12) {
                                        $singleItem->ischange = 1;
                                    } else if ($singleItem->changeno != "" && strlen($singleItem->changeno) == 12) {
                                        $singleItem->ischange = 1;
                                    } else {
                                        $singleItem->ischange = 0;
                                    }
                                } else if (strpos($singleItem->channel, "DHL") > 0 || strpos($singleItem->channel, "DHL") === 0) {
                                    if ($singleItem->turnno != "" && (strlen($singleItem->turnno) == 12 || strlen($singleItem->turnno) == 10)) {
                                        $singleItem->ischange = 1;
                                    } else if ($singleItem->changeno != "" && (strlen($singleItem->changeno) == 12 || strlen($singleItem->changeno) == 10)) {
                                        $singleItem->ischange = 1;
                                    } else {
                                        $singleItem->ischange = 0;
                                    }
                                } else if (strpos($singleItem->channel, "UPS") > 0 || strpos($singleItem->channel, "UPS") === 0) {
                                    if ($singleItem->turnno != "" && strlen($singleItem->turnno) == 18) {
                                        $singleItem->ischange = 1;
                                    } else if ($singleItem->changeno != "" && strlen($singleItem->changeno) == 18) {
                                        $singleItem->ischange = 1;
                                    } else {
                                        $singleItem->ischange = 0;
                                    }
                                } else if (strpos($singleItem->channel, "澳大利亚EMS") > 0 || strpos($singleItem->channel, "澳大利亚EMS") === 0) {
                                    if ($singleItem->turnno != "" && strlen($singleItem->turnno) == 13) {
                                        $singleItem->ischange = 1;
                                    } else if ($singleItem->changeno != "" && strlen($singleItem->changeno) == 13) {
                                        $singleItem->ischange = 1;
                                    } else {
                                        $singleItem->ischange = 0;
                                    }
                                } else {
                                    $singleItem->ischange = 1;
                                }
                                $singleItem->save();
                            }
                        } else {
                            echo $agentval->name."(时间：" . date("Y-m-d", $i) . ")的没有转单号数据<br>";
                        }
                        $i+= 86399;
                    }
                    echo $agentval->name."(时间：2013-04-01~" . date("Y-m-d") . ")的转单号数据更新成功<br>";
                } 
                $costprice = new costpriceFilter();
                $costprice->datetime = $costpriceMt;
                $moneyresult = false;
                if($agentval->name == "互联易"){
                    $moneyresult = $obj->getCostPriceHly($costprice);
                }else if($agentval->name == "圣达"){
                    $moneyresult = $obj->getCostPriceSd($costprice);
                }else if($agentval->name == "易邮"){
                    $moneyresult = $obj->getCostPriceHly($costprice);
                }         
                if($moneyresult){
                    foreach ($moneyresult as $moneyval) {
                        $channelNo = iconv("GB2312//IGNORE", "UTF-8", $moneyval->billid);
                        $costpriceItem = Application_Model_CostPrice::byCostPrice($channelNo);
                        if($costpriceItem == ""){
                            $costpriceItem = new Application_Model_CostPrice();
                        }
                        $costpriceItem->crDatetime = iconv("GB2312//IGNORE", "UTF-8", $moneyval->datetime);
                        $costpriceItem->channelNo =iconv("GB2312//IGNORE", "UTF-8",  $moneyval->billid);
                        $costpriceItem->num = iconv("GB2312//IGNORE", "UTF-8", $moneyval->num);
                        $costpriceItem->weight = iconv("GB2312//IGNORE", "UTF-8", $moneyval->weight);
                        $costpriceItem->bagweight = iconv("GB2312//IGNORE", "UTF-8", $moneyval->bagweight);
                        $costpriceItem->channel = iconv("GB2312//IGNORE", "UTF-8", $moneyval->channel);
                        $costpriceItem->destination = iconv("GB2312//IGNORE", "UTF-8", $moneyval->destination);
                        $costpriceItem->name = iconv("GB2312//IGNORE", "UTF-8", $moneyval->name);
                        $costpriceItem->money = iconv("GB2312//IGNORE", "UTF-8", $moneyval->money);
                        $costpriceItem->currency = iconv("GB2312//IGNORE", "UTF-8", $moneyval->currency);
                        $costpriceItem->remark = iconv("GB2312//IGNORE", "UTF-8", $moneyval->remark);
                        $costpriceItem->agentid = $agentval->id;
                        $costpriceItem->save();
                    }
                    echo  $agentval->name."(时间：$costpriceMt-".date("Y-m-d").")的成本价数据更新成功<br>";
                }else{
                    echo  $agentval->name."(时间：$costpriceMt)的没有成本价数据<br>";
                }
                
            }
        }
        $waybillItem = Application_Model_wayBillItem::getDelaySystemAll();
        foreach ($waybillItem as $waybillval){
            $single = Application_Model_Single::bySingle($waybillval->agentNo);
            if($single){
                if($waybillval->getChannelBy()->IsShipNo != 1){
                    $logistics = $single->turnno?$single->turnno:($single->changeno?$single->changeno:$single->outstoreno);
                    $isChange = 0;
                    $isChange = $this->getIsChangeByAgentNameAgentNo($waybillval->getChannelBy()->Name, $logistics,$waybillval->AgentNo);
                    if($isChange == 1){
                        $waybillval->logistics = $logistics;
                        $waybillval->lastWeight = $single->weight*1000;
                        $waybillval->lastVolumeWeight = $single->bagweight*1000;
                        $costprice = Application_Model_CostPrice::byCostPrice($waybillval->agentNo);
                        if($costprice){
                            $waybillval->costMoney =  $costprice->money;
                            echo "国际运单：".$waybillval->agentNo." 已上系统已更新转单号和成本价<br>";
                        }else{
                            echo "国际运单：".$waybillval->agentNo." 已出转单号暂未出成本价<br>";
                        }
                        $waybillval->save();
                        $single->ischange = 1;
                        $single->save();
                    }
                }
            }else{
                echo "国际运单：".$waybillval->agentNo." 没有上系统未出转单号<br>";
            }
        }
        exit;
    }
    
    function getIsChangeByAgentNameAgentNo($agentName,$logistics,$agentNo)
    {
        $isChange = 0;
        if (strpos($agentName, "联邦") > 0 || strpos($agentName, "联邦") === 0) {
            if ($logistics != "" && strlen($logistics) == 12) {
                if($logistics != $agentNo){
                    $isChange = 1;
                }
            }
        } else if (strpos($agentName, "DHL") > 0 || strpos($agentName, "DHL") === 0) {
            if ($logistics != "" && (strlen($logistics) == 12 || strlen($logistics) == 10)) {
                if($logistics != $agentNo){
                    $isChange = 1;
                }
            }
        } else if (strpos($agentName, "UPS") > 0 || strpos($agentName, "UPS") === 0) {
            if ($logistics != "" && strlen($logistics) == 18) {
                if($logistics != $agentNo){
                    $isChange = 1;
                }
            }
        } else if (strpos($agentName, "澳大利亚EMS") > 0 || strpos($agentName, "澳大利亚EMS") === 0) {
            if ($logistics != "" && strlen($logistics) == 13) {
                if($logistics != $agentNo){
                    $isChange = 1;
                }
            }
        } else {
            $isChange = 1;
        }
        return $isChange;
    }
    
    public function forovertimeAction()
    {
        Application_Model_Operate::addOperate(0, null, null, "检查国际运单中的超期运单", null);
        $billOutItem = Application_Model_wayBillItem::getDelayAll(Application_Model_wayBillItem::Interior_Outstorage);
        if($billOutItem){
            foreach ($billOutItem as $billOutval){
                $single = Application_Model_Single::bySingle($billOutval->agentNo);
                if(!$single) {
                    if ($billOutval->dateSend < date("Y-m-d H:i:s", strtotime(" -2 day "))) {
                        $billOutval->interior = Application_Model_wayBillItem::Interior_OverSystem;
                        $billOutval->save();
                    }
                }
            }
        }
        echo "上系统超期的运单检查完成<br>";
        $billSystemItem = Application_Model_wayBillItem::getDelayAll(Application_Model_wayBillItem::Interior_System);
        if($billSystemItem){
            foreach ($billSystemItem as $billSystemvalue) {
                if ($billSystemvalue->dateSend < date("Y-m-d H:i:s", strtotime(" -2 day "))) {
                    $billSystemvalue->interior = Application_Model_wayBillItem::Interior_Oversingleno;
                    $billSystemvalue->save();
                }
            }
        }
        echo "转到超期的运单检查完成<br>";
        $billTransportationItem = Application_Model_wayBillItem::getDelayAll(Application_Model_wayBillItem::Interior_Singleno);
        if($billTransportationItem){
            foreach ($billTransportationItem as $billTransportationvalue) {
                if ($billTransportationvalue->dateSend < date("Y-m-d H:i:s", strtotime(" -2 day "))) {
                    $billTransportationvalue->interior = Application_Model_wayBillItem::Interior_OutTransportation;
                    $billTransportationvalue->save();
                }
            }
        }
        echo "上网超期的运单检查完成<br>";
        $billSingleItem = Application_Model_wayBillItem::getDelayAll(Application_Model_wayBillItem::Interior_Transportation);
        if($billSingleItem){
            foreach ($billSingleItem as $billSingvalue) {
                $expresspriceItem = Application_Model_ExpressPrice::getPriceByExpressAndCity($billSingvalue->expressId, $billSingvalue->state);
                if($expresspriceItem){
                    $times = explode("~", $expresspriceItem->times);
                    if ($billSingvalue->dateSend < date("Y-m-d H:i:s", strtotime(" -$times[1] day "))) {
                        $billSingvalue->interior = Application_Model_wayBillItem::Interior_Overachieve;
                        $billSingvalue->save();
                    }
                }
            } 
        }
        echo "完成超期的运单检查完成<br>";
        exit;
    }
   
    /**
     * 代购超期
     */
    public function outtimeorderAction()
    {
        $orderUnItem = Application_Model_Order::getOrderAllByStatus(Application_Model_Order::STATUS_UNSEND);
        if($orderUnItem){
            foreach ($orderUnItem as $orderVal) {
                if($orderVal->datePaid < date("Y-m-d H:i:s", strtotime(" -4 day "))){
                    $orderVal->status = Application_Model_Order::STATUS_OUTTIME_UNSEND;
                    $orderVal->save();
                    Application_Model_Operate::addOperate(0, null, $orderVal->id, "代购设置超期发货", $orderVal->userId);
                }
            }
        }
        $orderSubItem = Application_Model_Order::getOrderAllByStatus(Application_Model_Order::STATUS_SUBSCRIBE);
        if($orderSubItem){
            foreach ($orderSubItem as $orderSubVal) {
                if($orderSubVal->dateShip < date("Y-m-d H:i:s", strtotime(" -4 day "))){
                    $orderSubVal->status = Application_Model_Order::STATUS_OUTTIME_UNSEND;
                    $orderSubVal->save();
                    Application_Model_Operate::addOperate(0, null, $orderSubVal->id, "预订代购设置超期发货", $orderSubVal->userId);
                }
            }
        }
        echo "代购超期未发货检查完成<br>";
        $this->outInStore();
    }
    private function outInStore()
    {
        $orderSellerItem = Application_Model_Order::getOrderAllByStatus(Application_Model_Order::STATUS_SELLER_SENDED);
        foreach ($orderSellerItem as $orderSellerVal) {
            $storeItem = Application_Model_StoreItem::getbyLogistics($orderSellerVal->logisticsNo);
            if($storeItem){
                $orderSellerVal->status = Application_Model_Order::STATUS_INSTORE;
                $orderSellerVal->save();
                Application_Model_Operate::addOperate(0, null, $orderSellerVal->id, "正常代购设置已入库", $orderSellerVal->userId);
                continue;
            }
            $this->AnalysisOutInStore($orderSellerVal);
        }
        $orderOutTimeItem = Application_Model_Order::getOrderAllByStatus(Application_Model_Order::STATUS_OUTTIME_INSTORE);
        foreach ($orderOutTimeItem as $orderSellerVal) {
            $storeItem = Application_Model_StoreItem::getbyLogistics($orderSellerVal->logisticsNo);
            if($storeItem){
                $orderSellerVal->status = Application_Model_Order::STATUS_INSTORE;
                $orderSellerVal->save();
                Application_Model_Operate::addOperate(0, null, $orderSellerVal->id, "超期收获代购设置已入库", $orderSellerVal->userId);
                continue;
            }
            $this->AnalysisOutInStore($orderSellerVal);
        }
        echo "代购超期收货检查完成<br>";
        exit;
    }
    private function AnalysisOutInStore($orderSellerVal)
    {
        if($orderSellerVal->consignTime != "" && $orderSellerVal->consignTime != null && $orderSellerVal->consignTime != "0000-00-00 00:00:00.000000" && $orderSellerVal->consignTime != "0000-00-00 00:00:00"){
            if($orderSellerVal->consignTime < date("Y-m-d H:i:s", strtotime(" -5 day "))){
                $orderSellerVal->status = Application_Model_Order::STATUS_OUTTIME_INSTORE;
                $orderSellerVal->save();
                Application_Model_Operate::addOperate(0, null, $orderSellerVal->id, "发货代购设置超期收货", $orderSellerVal->userId);
            }
            if($orderSellerVal->consignTime < date("Y-m-d H:i:s", strtotime(" -10 day "))){
                $orderSellerVal->status = Application_Model_Order::STATUS_OUTTIME_FIN;
                $orderSellerVal->save();
                Application_Model_Operate::addOperate(0, null, $orderSellerVal->id, "发货代购设置财务风险", $orderSellerVal->userId);
            }
            return true;
        }
        if($orderSellerVal->dateShip != "" && $orderSellerVal->dateShip != null && $orderSellerVal->dateShip != "0000-00-00 00:00:00.000000" && $orderSellerVal->dateShip != "0000-00-00 00:00:00"){
            if($orderSellerVal->dateShip < date("Y-m-d H:i:s", strtotime(" -5 day "))){
                $orderSellerVal->status = Application_Model_Order::STATUS_OUTTIME_INSTORE;
                $orderSellerVal->save();
                Application_Model_Operate::addOperate(0, null, $orderSellerVal->id, "预订代购设置超期收货", $orderSellerVal->userId);
            }
            if($orderSellerVal->dateShip < date("Y-m-d H:i:s", strtotime(" -10 day "))){
                $orderSellerVal->status = Application_Model_Order::STATUS_OUTTIME_FIN;
                $orderSellerVal->save();
                Application_Model_Operate::addOperate(0, null, $orderSellerVal->id, "预订代购设置财务风险", $orderSellerVal->userId);
            }
            return true;
        }
        if($orderSellerVal->datePaid < date("Y-m-d H:i:s", strtotime(" -5 day ")) && $orderSellerVal->datePaid != "0000-00-00 00:00:00.000000" && $orderSellerVal->datePaid != "0000-00-00 00:00:00"){
            $orderSellerVal->status = Application_Model_Order::STATUS_OUTTIME_INSTORE;
            $orderSellerVal->save();
            Application_Model_Operate::addOperate(0, null, $orderSellerVal->id, "付款代购设置财务风险", $orderSellerVal->userId);
        }
        if($orderSellerVal->datePaid < date("Y-m-d H:i:s", strtotime(" -10 day ")) && $orderSellerVal->datePaid != "0000-00-00 00:00:00.000000" && $orderSellerVal->datePaid != "0000-00-00 00:00:00"){
            $orderSellerVal->status = Application_Model_Order::STATUS_OUTTIME_FIN;
            $orderSellerVal->save();
            Application_Model_Operate::addOperate(0, null, $orderSellerVal->id, "付款代购设置财务风险", $orderSellerVal->userId);
        }
        return true;
    } 
    

    public function deliveredAction()
    {
        Application_Model_Operate::addOperate(0, null, null, "检查国际运单中的签收运单", null);
        $billOutItem = Application_Model_wayBillItem::getOutDelivered();
        foreach ($billOutItem as $outVal) {
            $no = $outVal->Logistics;
            $content = '';
            $isUrl = 0;
            $express = $outVal->getExpressBy();
            if($express->TrackType == Application_Model_Express::TRACK_TYPE_KUAIDI100 
                    || $express->TrackType == Application_Model_Express::TRACK_TYPE_KUAIDI_LINK){
                $type = $express->TrackNo;
                $content = '';
                $isUrl = $express->TrackType == Application_Model_Express::TRACK_TYPE_KUAIDI_LINK?0:1;
                if ($isUrl) {
                    $content = Uuch_Util::express($type, $no);
                    $result = strip_tags($content);
                    if(strpos($result,":00Delivered") > 0 || strpos($result,":00Delivered") === 0)
                    {
                        $outVal->Status = Application_Model_wayBillItem::STATUS_Complated;
                        $outVal->Interior = Application_Model_wayBillItem::Interior_Achieve;
                        $outVal->save();
                        $outVal->addBillLog(Application_Model_wayBillItem::Interior_Achieve);
                        echo $outVal->BillNO."已经完成发货，用户已经收货！<br>";
                    } else if(strpos($result,"已派送并签收") > 0 || strpos($result,"已派送并签收") === 0) {
                        $outVal->Status = Application_Model_wayBillItem::STATUS_Complated;
                        $outVal->Interior = Application_Model_wayBillItem::Interior_Achieve;
                        $outVal->save();
                        $outVal->addBillLog(Application_Model_wayBillItem::Interior_Achieve);
                        echo $outVal->BillNO."已经完成发货，用户已经收货！<br>";
                    } else if(strpos($result,"投递并签收") > 0 || strpos($result,"投递并签收") === 0) {
                        $outVal->Status = Application_Model_wayBillItem::STATUS_Complated;
                        $outVal->Interior = Application_Model_wayBillItem::Interior_Achieve;
                        $outVal->save();
                        $outVal->addBillLog(Application_Model_wayBillItem::Interior_Achieve);
                        echo $outVal->BillNO."已经完成发货，用户已经收货！<br>";
                    }
                } 
            }else if($express->TrackType == Application_Model_Express::TRACK_TYPE_3TH){
                $sg = new Uuch_SpeedPostAPI();
                $result = $sg->query($no);
                foreach ($result as $key => $item){
                    if($key == 0)
                    {
                        if($item->status == "Delivered"){
                            $outVal->Status = Application_Model_wayBillItem::STATUS_Complated;
                            $outVal->Interior = Application_Model_wayBillItem::Interior_Achieve;
                            $outVal->save();
                            $outVal->addBillLog(Application_Model_wayBillItem::Interior_Achieve);
                            echo $outVal->BillNO."已经完成发货，用户已经收货！<br>";
                        }
                        break;
                    }
                }
            }   
        }
        echo "国际运单完成签收检查完成";
        exit;
    }
    
    public function recommendAction()
    {
        $wayMaxId = Application_Model_OptionItem::getSearch("recommendMaxWayId");       
        $recommendWayItem = Application_Model_wayBillItem::ByMaxId($wayMaxId->Myvalue);
        if($recommendWayItem) {
            foreach ($recommendWayItem as $recommendWayVal) {
                $recommendItem = Application_Model_Recommend::ByUserIdReUserId($recommendWayVal->UserId, null);
                if($recommendItem){ 
                   $rewardItem1=Application_Model_Reward::bybillNo($recommendWayVal->BillNo);                   
                   if($rewardItem1) continue;  
                    $rewardItem = new Application_Model_Reward();
                    $rewardItem->UserId = $recommendWayVal->UserId;
                    $rewardItem->BillNo = $recommendWayVal->BillNo;
                    $rewardItem->Money = "0.00";
                    $rewardItem->Rebate = "0.00";
                    $rewardItem->ReUserId = $recommendItem->ReUserId;
                    $rewardItem->IsAbled = Application_Model_Reward::IsAbled_Unfinished;
                    $rewardItem->CreateTime = date("Y-m-d H:i:s");
                    $rewardItem->save();
                    echo "国际运单".$recommendWayVal->BillNo."返利<br>";
                }
            }
        }
        $maxId = Application_Model_wayBillItem::MaxId();       
        $wayMaxId->Myvalue = $maxId;
        $wayMaxId->save();
        
       $unRewardItem = Application_Model_Reward::ByIsAbled(Application_Model_Reward::IsAbled_Unfinished);
       foreach ($unRewardItem as $unRewardVal) {
           $waybillItem = Application_Model_wayBillItem::bybillNo($unRewardVal->BillNo);
           if($waybillItem && $waybillItem->Interior == Application_Model_wayBillItem::Interior_Achieve) {
               $unRewardVal->Money = $waybillItem->LastMoney;
               $unRewardVal->Rebate = $waybillItem->LastMoney*(Application_Model_Reward::Rebates_Proportion);
               $unRewardVal->IsAbled = Application_Model_Reward::IsAbled_Complete;
               $unRewardVal->save();
               echo "国际运单".$waybillItem->BillNo."返利可以领取<br>";
           }
       }
       exit;
    }
    
    public function taobaopriceAction()
    {
        echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
        $orderItem = Application_Model_Order::ByDateOrder("2013-11-01","2013-11-25");
        $taobao = new Uuch_Reader_TaobaoReader();
        $Income = 0;
        $Expenditure = 0;
        $taobaoMoney = 0;
        $otherMoney = 0;
        $fee = 0;
        $i = 0;
        $arrSign = Application_Model_Taobaoapi::getSignAll();
        foreach ($orderItem as  $orderval) {
            if($orderval["procureNo"] != NULL){
                $taobaoid = substr($orderval["procureNo"], -4);
//                if($taobaoid == "6538" || $taobaoid == "5899" || $taobaoid == "9936" || $taobaoid == "3662" || $taobaoid == "3852"){
                if(in_array($taobaoid, $arrSign)){
                    $result = $taobao->taobaowlprice($orderval["procureNo"]);  
//                    var_dump($result);$i++;if($i>10){exit;}
                    if($result){  
                        echo $orderval["procureNo"].",";
                        $priceItem = Application_Model_Order::ByProcureNo($orderval["procureNo"]);
                        echo $priceItem["sum"].",";
                        echo $priceItem["shipFee"].",";
                        $Income += $priceItem["sum"];
                        $taobaoMoney += $priceItem["sum"];
                        $money = 0;
                        if($result->trade->orders){
                            foreach ($result->trade->orders->order as $orderValB) {  
                                $Expenditure += $orderValB->total_fee;
                                $money += $orderValB->total_fee;
                            }
                        } else {
                            $money = "BUG";
                        }
                        echo $money.",";
                        if($result->trade->post_fee){
                            foreach ($result->trade->post_fee as $postFee){
                                echo $postFee.",";
                                $fee += $postFee;
                            }
                        } else {
                            echo "BUG,";
                        }
                        echo $taobaoid;
                        echo "<br>";
                    }
                }else{
                    $priceItem = Application_Model_Order::ByProcureNo($orderval["procureNo"]);
                    $otherMoney += $priceItem["sum"];
                }
            }
        }
        echo "总收入为：".$Income."；预订淘宝总支出：".$taobaoMoney."；实际淘宝总支出：".$Expenditure."；淘宝总运费：".$fee."；其他总支出：".$otherMoney;
        exit;
    }
    public function taobaoonepriceAction()
    {
        echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
        $orderItem = Application_Model_Order::load("26138");
        $taobao = new Uuch_Reader_TaobaoReader();
        $taobaoid = substr($orderItem->procureNo, -4);
        if($taobaoid == "6538" || $taobaoid == "5899" || $taobaoid == "9936" || $taobaoid == "3662" || $taobaoid == "3852"){
            $result = $taobao->taobaowlprice($orderItem->procureNo);   
            foreach ($result->trade->orders->order as $orderValB) { 
                var_dump($orderValB);
                echo $orderValB->total_fee."<br>";
                foreach ($orderValB->total_fee as $taotafeeVal) {
                    var_dump($taotafeeVal);
                    echo "<br>";
                }
            }
            var_dump($result);
        }
        exit;
    }
    
    public function allpaypalAction()
    {
        Application_Model_Operate::addOperate(0, null, 0, "获取Paypal的充值日志", 0);
        echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
        $start_time = time() - 3600*24*2;
        $iso_start = date('Y-m-d\T00:00:00\Z', $start_time);
        $nvpStr = "&STARTDATE=$iso_start";
        $end_time = time() - 3600*24;
        $iso_end = date('Y-m-d\T23:59:59\Z', $end_time);
        $nvpStr.="&ENDDATE=$iso_end";

        $paypal = new Uuch_PayPal();
        $resArray = $paypal->hash_call("TransactionSearch", $nvpStr);
        
        $count = 0;
        while (isset($resArray["L_TRANSACTIONID" . $count])) {
            $count++;
        }
        $ID = 0;
        while ($count > 0) {
            $paybillItem = Application_Model_PayBill::bypayIdTxnId(Application_Model_PayBill::PAY_PAYPAL, $resArray["L_TRANSACTIONID" . $ID]);
            if(!$paybillItem){
                $payLogItem = Application_Model_PaypalLog::byTxnId($resArray["L_TRANSACTIONID" . $ID]);
                if($payLogItem){
                    if($payLogItem->paypalStatus != $resArray["L_STATUS" . $ID]){
                        $payLogItem->IsDel = 1;
                        $payLogItem->save();
                        $paypalLogItem = new Application_Model_PaypalLog();
                        $paypalLogItem->TxnId = $resArray["L_TRANSACTIONID" . $ID];
                        $paypalLogItem->DateCreated = date("Y-m-d H:i:s",  strtotime($resArray["L_TIMESTAMP" . $ID]));
                        $paypalLogItem->PaypalName = $resArray["L_NAME" . $ID];
                        $paypalLogItem->Amount = $resArray["L_AMT" . $ID];
                        $paypalLogItem->PaypalStatus = $resArray["L_STATUS" . $ID];
                        $paypalLogItem->PaypalEmail = isset($resArray["L_EMAIL".$ID])?$resArray["L_EMAIL".$ID]:"";
                        $paypalLogItem->FeeAmt = $resArray["L_FEEAMT" . $ID];
                        $paypalLogItem->Status = Application_Model_PaypalLog::Status_Default;
                        $paypalLogItem->save();
                    }
                } else {
                    $paypalLogItem = new Application_Model_PaypalLog();
                    $paypalLogItem->TxnId = $resArray["L_TRANSACTIONID" . $ID];
                    $paypalLogItem->DateCreated = date("Y-m-d H:i:s",  strtotime($resArray["L_TIMESTAMP" . $ID]));
                    $paypalLogItem->PaypalName = $resArray["L_NAME" . $ID];
                    $paypalLogItem->Amount = $resArray["L_AMT" . $ID];
                    $paypalLogItem->PaypalStatus = $resArray["L_STATUS" . $ID];
                    $paypalLogItem->PaypalEmail = isset($resArray["L_EMAIL".$ID])?$resArray["L_EMAIL".$ID]:"";
                    $paypalLogItem->FeeAmt = $resArray["L_FEEAMT" . $ID];
                    $paypalLogItem->Status = Application_Model_PaypalLog::Status_Default;
                    $paypalLogItem->save();
                    echo "Paypal流水号：".$resArray["L_TRANSACTIONID" . $ID]." 在用户支付记录中没有找到，请进Paypal日志中操作。<br>";
                }
            }
            $count--;
            $ID++;
        }
        exit;
    }

    public function testAction()
    {
        
//        Uuch_eub::createdEub();  LX900721585CN
//        $billNo = "LX900721563CN";
//        $billNo = $this->getSafeParam("billno");
//        Uuch_eub::selbill($billNo);
//        Uuch_Tcpdf::createdPdf("15751");
        $id = $this->getSafeParam("id");
        Uuch_Tcpdf::printPDF("X4",$id,"1.12","LN153555526CN");
//        echo 123;
        exit;
    }
    
    public function taobaotopurlAction()
    {
        $id = $this->getSafeParam("id");
        $order = Application_Model_Order::load($id);
        $orderItem = $order->getItems();
        foreach ($orderItem as $orVal) {
            $product = Application_Model_Product::load($orVal->productId);
            if (strpos($product->url, "taobao") > 0 || strpos($product->url, "tmall") > 0) {
                $taobalReader = new Uuch_Reader_TaobaoReader();
                $topUrl = $taobalReader->getOneTopUrl($product->name, $product->url);
                if ($topUrl != NULL) {
                    echo "返利地址为：". $topUrl;
                } else {
                    echo "没有获取到返利地址";
                }
            } else {
                echo "不是淘宝订单";
            }
        }
        exit;
    }
    
    public function orderdataAction() {
        ini_set('memory_limit', '512M');
        $startTime = $this->getSafeParam("start");
        $endTime = $this->getSafeParam("end");
        if($startTime == "") {
            echo "起始时间不能为空！<br/>";
            exit();
        }
        if($endTime == "") {
            $report = new Application_Model_DbTable_Report();
            $orderItem = $report->OrderData("all",$startTime);
            $orderNewItem = $report->OrderData("new",$startTime);
            $orderOldItem = $report->OrderData("old",$startTime);
            Application_Model_Data::DisposeOrderData($startTime,$orderItem,$orderNewItem,$orderOldItem);
        } else {
            $start = strtotime($startTime)<strtotime($endTime)?strtotime($startTime):strtotime($endTime);
            $end = strtotime($startTime)>strtotime($endTime)?strtotime($startTime):strtotime($endTime);
            if($end - $start >= 2592000) {
                echo "查询时间间隔不能超过30天！<br/>";
                exit();
            }
            for ($index = $start; $index <= $end; $index+=86400) {
                $dataTime = date("Y-m-d",$index);
                $report = new Application_Model_DbTable_Report();
                $orderItem = $report->OrderData("all",$dataTime);
                $orderNewItem = $report->OrderData("new",$dataTime);
                $orderOldItem = $report->OrderData("old",$dataTime);
                Application_Model_Data::DisposeOrderData($dataTime,$orderItem,$orderNewItem,$orderOldItem);
            }
        }
        echo "成功";
        exit;
    }
    
    public function waydataAction() {
        ini_set('memory_limit', '512M');
        $startTime = $this->getSafeParam("start");
        $endTime = $this->getSafeParam("end");
        if($startTime == "") {
            echo "起始时间不能为空！<br/>";
            exit();
        }
        if($endTime == "") {
            $report = new Application_Model_DbTable_Report();
            $wayItem = $report->WayData("all",$startTime);
            $wayNewItem = $report->WayData("new",$startTime);
            $wayOldItem = $report->WayData("old",$startTime);
            Application_Model_Data::DisposeWayData($startTime, $wayItem, $wayNewItem, $wayOldItem);
        } else {
            $start = strtotime($startTime)<strtotime($endTime)?strtotime($startTime):strtotime($endTime);
            $end = strtotime($startTime)>strtotime($endTime)?strtotime($startTime):strtotime($endTime);
            if($end - $start >= 2592000) {
                echo "查询时间间隔不能超过30天！<br/>";
                exit();
            }
            for ($index = $start; $index <= $end; $index+=86400) {
                $dataTime = date("Y-m-d",$index);
                $report = new Application_Model_DbTable_Report();
                $wayItem = $report->WayData("all",$dataTime);
                $wayNewItem = $report->WayData("new",$dataTime);
                $wayOldItem = $report->WayData("old",$dataTime);
                Application_Model_Data::DisposeWayData($dataTime, $wayItem, $wayNewItem, $wayOldItem);
            }
        }
        echo "成功";
        exit;
    }
    
    public function storedataAction() {
        ini_set('memory_limit', '512M');
        $startTime = $this->getSafeParam("start");
        $endTime = $this->getSafeParam("end");
        if($startTime == "") {
            echo "起始时间不能为空！<br/>";
            exit();
        }
        if($endTime == "") {
            $report = new Application_Model_DbTable_Report();
            $storeItem = $report->StoreData("all",$startTime);
            $storeNewItem = $report->StoreData("new",$startTime);
            $storeOldItem = $report->StoreData("old",$startTime);
            Application_Model_Data::DisposeStoreData($startTime, $storeItem, $storeNewItem, $storeOldItem);
        } else {
            $start = strtotime($startTime)<strtotime($endTime)?strtotime($startTime):strtotime($endTime);
            $end = strtotime($startTime)>strtotime($endTime)?strtotime($startTime):strtotime($endTime);
            if($end - $start >= 2592000) {
                echo "查询时间间隔不能超过30天！<br/>";
                exit();
            }
            for ($index = $start; $index <= $end; $index+=86400) {
                $dataTime = date("Y-m-d",$index);
                $report = new Application_Model_DbTable_Report();
                $storeItem = $report->StoreData("all",$dataTime);
                $storeNewItem = $report->StoreData("new",$dataTime);
                $storeOldItem = $report->StoreData("old",$dataTime);
                Application_Model_Data::DisposeStoreData($dataTime, $storeItem, $storeNewItem, $storeOldItem);
            }
        }
        echo "成功";
        exit;
    }
    
    public function userdataAction() {
        ini_set('memory_limit', '512M');
        $startTime = $this->getSafeParam("start");
        $endTime = $this->getSafeParam("end");
        if($startTime == "") {
            echo "起始时间不能为空！<br/>";
            exit();
        }
        if($endTime == "") {
            $userSearch = new Application_Model_Filter_UserSearch();
            $userSearch->dateselect = "regedit";
            $userSearch->starttime = $startTime;
            $userSearch->endtime = $startTime;
            $userSearch->isUniteLogin = 1;
            $userItem  = Application_Model_User::ByAll($userSearch);
            Application_Model_Data::disposeUserData($startTime,$userItem);
        } else {
            $start = strtotime($startTime)<strtotime($endTime)?strtotime($startTime):strtotime($endTime);
            $end = strtotime($startTime)>strtotime($endTime)?strtotime($startTime):strtotime($endTime);
            if($end - $start >= 2592000) {
                echo "查询时间间隔不能超过30天！<br/>";
                exit();
            }
            for ($index = $start; $index <= $end; $index+=86400) {
                $dataTime = date("Y-m-d",$index);
                $userSearch = new Application_Model_Filter_UserSearch();
                $userSearch->dateselect = "regedit";
                $userSearch->starttime = $dataTime;
                $userSearch->endtime = $dataTime;
                $userSearch->isUniteLogin = 1;
                $userItem  = Application_Model_User::ByAll($userSearch);
                Application_Model_Data::disposeUserData($dataTime,$userItem);
            }
        }
        echo "成功";
        exit();
    }
    
    public function birthdayAction() {
        Application_Model_Operate::addOperate(0, null, 0, "发放生日优惠券", 0);
        $date = date("m-d");
        $userItem = Application_Model_Profile::getBirthDayByDate($date);
        foreach ($userItem as $userVal) {
            $user = Application_Model_User::load($userVal->UserId);
            if($user->Account->userGrade<Application_Model_UserAccount::User_Silver) {
                continue;
            }
            $couponItem = Application_Model_Coupon::getcouponByUserIdBatchNo($userVal->UserId, "BirthdayReward");
            $isReceive = false;
            foreach ($couponItem as $couponVal) {
                if(date("Y",  strtotime("$couponVal->DateCreated")) == date("Y")){
                    $isReceive = true;
                    break;
                }
            }
            if(!$isReceive){
                $user->Account->BirthdayReward();
            }
        }
        echo "发放生日优惠券成功！";exit;
    }
}
